# -*- coding: utf-8 -*-

import os, sys, fcntl
from scapy.sendrecv import sniff
from scapy.packet import Raw
#from scapy.fields import Field
from scapy.layers.inet import IP,UDP
from scapy.layers.rtp import RTP, _rtp_payload_types
from scapy.layers.sip import SIP
from scapy.utils import get_temp_file
from operator import attrgetter

# sox -m -t ul file1 -t ul file2 -t alsa gain -6

class Output:
    def __init__(self):
      self.files={}
      self.payloads={}
    
    def write(self,pkt):
      
      	sig = pkt[IP].src + '.' + str(pkt.sport) + '->' + pkt[IP].src + '.' + str(pkt.dport) 
	
	if sig not in self.files:
	  print 'RTP stream, session: ' + str(pkt[RTP].sourcesync) + ', payload: ' + _rtp_payload_types[pkt[RTP].fields['payload']] + ', addresses: ' + sig 
	  self.files[sig]=open(sig + '.raw','w')
	  self.payloads[sig]=[]
	
	self.payloads[sig].append(pkt[RTP])
	
	if len(self.payloads[sig]) == 10000:
	  ordered = sorted(self.payloads[sig], key=attrgetter("sequence"))
	  for p in ordered:
	    self.files[sig].write(p[Raw].load)
	  self.payloads[sig]=[]
	

    def close(self):
      for f in self.files:
	self.files[f].close()

class Sniffer:
  
  def __init__(self,offline=None, iface=None):
    self.offline=offline
    self.iface=iface
    self.lst=None
    self.out = Output()
    
  def play(self,pkt):
  
    if pkt:
      if pkt.haslayer(SIP):
      	print pkt[SIP].show()
	pass
	
      if pkt.haslayer(RTP):
	#self.out.write(pkt)
	pass
  
  def start(self,**kargs):
      
    try:  
	if self.lst is None:
	    sniff(offline=self.offline, iface=self.iface, store=0, prn=self.play, **kargs)
	else:
	    for p in self.lst:
		self.play(p)

    except Exception: 
	self.out.close()
	raise


if __name__ == "__main__":
    
    o=None
    if len(sys.argv)==2:
      o=sys.argv[1]
    
    s=Sniffer(offline=o)
    try:
      s.start()
    except (KeyboardInterrupt, SystemExit):
      print '! Received keyboard interrupt, quitting.'
